package com.leyou.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.enums.ExceptionEnum;
import com.leyou.exception.LyException;
import com.leyou.upload.config.UploadProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: wzh
 * @Date: 2019/3/20 06:44
 * @Description:图片上传
 */
@Service
@Slf4j
@EnableConfigurationProperties({UploadProperties.class}) //加载自定义配置文件类
public class UploadService {

    @Autowired
    private UploadProperties Prop;
    @Autowired
    private FastFileStorageClient storageClient;
    // 支持的文件类型
    //private static final List<String> ALLOW_TYPES = Arrays.asList("image/png", "image/jpeg","image/bmp");
    public String uploadImage(MultipartFile file) {
        try {
            //校验文件类型
            String contentType = file.getContentType();
            if (!Prop.getAllowTypes().contains(contentType)){
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            //校验文件内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null){
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }

            //将图片上传到FastDFS
            //获取文件后缀名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            StorePath storePath = this.storageClient.uploadFile(
                    file.getInputStream(), file.getSize(), extension, null);
            //返回图片路径
            return Prop.getBaseUrl() + storePath.getFullPath();

        }catch (Exception e){
            //上传文件失败
            log.error("上传文件失败",e);
            throw new LyException(ExceptionEnum.BRAND_SAVE_ERROR);
        }

    }
}
